package com.hyt.it.ogt.kq.main.controller.bm;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.ObjectUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.core.util.FastJsonUtil;
import com.hyt.exception.annotation.ThrowsAdvice;
import com.hyt.it.ogt.kq.common.bm.utils.Constant;
import com.hyt.it.ogt.kq.common.config.ConfigManager;
import com.hyt.it.ogt.kq.common.gov.config.swagger.ApiVersionConstant;
import com.hyt.it.ogt.kq.main.controller.base.BaseController;
import com.hyt.it.ogt.kq.service.bm.model.entity.*;
import com.hyt.it.ogt.kq.service.bm.model.vo.*;
import com.hyt.it.ogt.kq.service.bm.service.*;
import com.hyt.it.ogt.kq.service.bm.service.stcenter.IStcenterStudentPayService;
import com.hyt.log.annotation.Log;
import com.hyt.loginfo.model.User;
import com.hyt.loginfo.service.IBaseLoginService;
import com.hyt.progress.creator.anno.ProgressAnno;
import com.hyt.swagger.ApiVersion;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;

/**
 * 考生审核表 前端控制器
 *
 * @author huangwu
 * @since 2020-05-15
 */
@RestController
@Api(tags = "11.管理端：考生审核接口", value = "考生审核信息接口")
@ApiSort(value = 11)
@Slf4j
@RequestMapping("/bm/student-verify")
public class StudentVerifyController extends BaseController {

    @Resource
    private IStudentSubjectService iStudentSubjectService;
    @Resource
    private IStudentProjectService iStudentProjectService;
    @Resource
    private IStudentVerifyService iStudentVerifyService;
    @Resource
    private IStudentInfoService iStudentInfoService;
    @Resource
    IProjectService iProjectService;
    @Resource
    IBaseLoginService iBaseLoginService;
    @Resource
    private IStcenterStudentPayService iStcenterStudentPayService;
    @Resource
    private INonOpenService iNonOpenService;

    @Resource
    private ConfigManager configManager;

    @ApiOperation(value = "11.1.1  管理端：查询考生列表", notes = "20000:成功； 31111101：报名项目信息不存在", response = StudentListInfo.class)
    @ApiOperationSort(value = 1)
    @ApiVersion(group = ApiVersionConstant.V2_4_10)
    @ThrowsAdvice(code = 31111102, print = "查询考生列表异常")
    @GetMapping(value = "/list")
    public ApiResponse<IPage<StudentListVo>> queryPage(StudentInfoParam param) {
        Project project = iProjectService.getById(param.getProjectId());
        if (null == project) {
            return ApiResponse.<IPage<StudentListVo>>builder()
                    .code(31111101)
                    .build();
        }
        Set<String> deptIds = iBaseLoginService.getDeptIds();
        param.setDeptIds(deptIds);

        // 列表页面查询接口
        IPage<StudentListVo> studentList = iStudentSubjectService.getStudentList(param);
        return ApiResponse.<IPage<StudentListVo>>builder()
                .code(Constant.RESPONSE_CODE_SUCCESS)
                .data(studentList)
                .build();
    }


    @ApiOperation(value = "11.1.2  管理端：删除考生", notes = "20000:成功")
    @ApiOperationSort(value = 2)
    @ThrowsAdvice(code = 31111201, print = "批量删除考生异常")
    @Log(module = "考生审核管理", business = "批量删除考生")
    @DeleteMapping(value = "/deleteStudent")
    public ApiResponse<String> deleteStudent(@ApiParam(value = "考生IDS，用逗号隔开") String studentId) throws Exception {
        if (StringUtils.isEmpty(studentId)) {
            return ApiResponse.<String>builder().code(Constant.RESPONSE_CODE_14035).data("未选择任何考生！").build();
        }
        User user = getUser();
		log.info("# deleteStudent studentId:{}, operateuser:{}", studentId, FastJsonUtil.getBeanToJson(user));
		
		List<String> studentIds = CharSequenceUtil.split(studentId, StrPool.COMMA);
		for (String studentIdText : studentIds) {
			StudentProject studentProject= iStudentProjectService.getById(studentIdText);
			if (ObjectUtil.isEmpty(studentProject)) {
				continue;
			}
			try {
			    // 根据studentid查考生信息
	            StudentDetail studentDetail = iStudentInfoService.getStudentInfo(studentProject.getProjectId(), studentIdText);
	            log.info("# deleteStudent studentId:{},operateuser:{}, studentDetail:{}", studentIdText, FastJsonUtil.getBeanToJson(user), FastJsonUtil.getBeanToJson(studentDetail));
            } catch (Exception e) {
                
            }
            
            boolean hasPay = iStcenterStudentPayService.querystudentSubjectPayRecord(studentId, null, studentProject.getProjectId());
            if (hasPay) {
                return ApiResponse.<String>builder().code(Constant.RESPONSE_CODE_31111501).data("考生已缴费，不能删除").build();
            }
            // 删除考生的基础数据
            iStudentSubjectService.deleteStudent(studentProject.getProjectId(), studentIdText);
            
            // 如果报名资格有数据，修改报名资格的数据为未报名
            QueryWrapper<NonOpenInfo> nonOpenInfoQueryWrapper = new QueryWrapper<>();
            nonOpenInfoQueryWrapper.lambda()
                .eq(NonOpenInfo::getProjectId, studentProject.getProjectId())
                .eq(NonOpenInfo::getCardNumber, studentProject.getCardNumber())
                .last("LIMIT 1");
            
            NonOpenInfo nonOpenInfo = iNonOpenService.getOne(nonOpenInfoQueryWrapper);
            if(null != nonOpenInfo) {
                nonOpenInfo.setIsBm(Boolean.FALSE);
                nonOpenInfo.setUpdateDate(LocalDateTime.now());
                nonOpenInfo.setUpdateBy(user.getId());
                iNonOpenService.saveOrUpdate(nonOpenInfo);
            }
        }
        return ApiResponse.<String>builder().code(Constant.RESPONSE_CODE_SUCCESS).data("删除考生成功！").build();
    }

    @ApiOperation(value = "11.1.3  管理端：审核考生", notes = "20000:成功;15008审核失败")
    @ApiOperationSort(value = 3)
    @Log(module = "考生审核管理", business = "审核考生")
    @ThrowsAdvice(code = 31111301, print = "管理端审核考生异常")
    @PostMapping(value = "/auditStudent")
    public ApiResponse<Object> auditStudent(@RequestBody StudentVerify sVerify) {
        if (StringUtils.isEmpty(sVerify.getVerifyBy())) {
            sVerify.setVerifyBy(getUserId());
        }
        if (null == sVerify.getVerifyDatetime()) {
            sVerify.setVerifyDatetime(LocalDateTime.now());
        }
        return iStudentVerifyService.auditStudentSubject(sVerify);
    }

    @ApiOperation(value = "11.1.4  管理端：查询考生详情", notes = "20000:成功，15009：查询失败", response = StudentDetail.class)
    @ApiOperationSort(value = 4)
    @ThrowsAdvice(code = 31111401, print = "管理端：查询考生详情异常")
    @GetMapping(value = "/info")
    public ApiResponse<StudentDetail> info(String projectId, String studentId) throws Exception {
        StudentDetail studentDetail;
        studentDetail = iStudentInfoService.getStudentInfo(projectId, studentId);
        if (studentDetail != null) {
            return ApiResponse.<StudentDetail>builder().code(Constant.RESPONSE_CODE_SUCCESS).data(studentDetail).build();
        } else {
            return ApiResponse.<StudentDetail>builder().code(31111401).build();
        }
    }

    @ApiOperation(value = "11.1.5  管理端：删除科目", notes = "20000:成功")
    @ApiOperationSort(value = 5)
    @Log(module = "考生审核管理", business = "删除考生科目")
    @ThrowsAdvice(code = 31111502, print = "删除科目异常")
    @PostMapping(value = "/deleteStudentSubject")
    public ApiResponse<String> deleteStudentSubject(@RequestBody StudentSubject studentSubject) {
        iStudentVerifyService.deleteStudentSubject(studentSubject);
        return ApiResponse.<String>builder()
                .code(Constant.RESPONSE_CODE_SUCCESS)
                .data("删除考生科目成功！")
                .build();
    }

    @ApiOperation(value = "11.1.6 管理端： 添加考生报名科目", notes = "20000:成功；15010：添加考生报名科目数据失败")
    @ApiOperationSort(value = 6)
    @Log(module = "考生审核管理", business = "添加考生报名科目")
    @ThrowsAdvice(code = 31111601, print = "添加考生报名科目异常")
    @PostMapping(value = "/addSubject")
    public ApiResponse<String> addSubject(@RequestBody StuSubjectVo stuSubjectVo) {
        String userId = getUserId();
        stuSubjectVo.setCurrentLoginUserId(userId);
        
        iStudentVerifyService.addSubject(stuSubjectVo);
        return ApiResponse.<String>builder().code(Constant.RESPONSE_CODE_SUCCESS).data("报名科目成功！").build();
    }


    @ApiOperation(value = "11.1.7 管理端： 导出考生列表", notes = "20000:成功；15012：添导出考生列表失败")
    @ApiOperationSort(value = 7)
    @GetMapping(value = "/exportStudentList")
    @Log(module = "考生管理", business = "导出考生")
    @ThrowsAdvice(code = 31110107, print = "导出考生列表，请联系系统管理员")
    public void exportStudentList(StudentInfoParam param, String queryStr, String projectId, String auditState, HttpServletResponse response) throws Exception {
        log.info("# 11.1.7 管理端：导出考生列表请求参数{}", FastJsonUtil.getBeanToJson(param));

        User sysUser = getUser();
        log.info("# 11.1.7 管理端：导出考生列表sysUser={}", FastJsonUtil.getBeanToJson(sysUser));
        param.setOfficeId(this.getOfficeId());
        param.setDeptIds(iBaseLoginService.getDeptIds());
        iStudentInfoService.exportStudentList(response, param);
    }

    @ApiOperation(value = "11.1.8 查看考生报名科目", notes = "20000:成功 ")
    @ApiOperationSort(value = 8)
    @ThrowsAdvice(code = 15004, print = "查看考生报名科目异常")
    @GetMapping(value = "/query/{projectId}/{studentId}")
    public ApiResponse<List<StudentSubjectDetailVo>> query(@PathVariable String projectId, @PathVariable String studentId) {
        List<StudentSubjectDetailVo> studentInfo = iStudentInfoService.getProjectSubjectByStuId(projectId, studentId);
        if (studentInfo != null) {
            return ApiResponse.<List<StudentSubjectDetailVo>>builder().code(Constant.RESPONSE_CODE_SUCCESS).data(studentInfo).build();
        } else {
            return ApiResponse.<List<StudentSubjectDetailVo>>builder().code(Constant.RESPONSE_CODE_15004).data(studentInfo).build();
        }
    }

    @ApiOperation(value = "11.1.10 管理端： 通过华为云导出考生列表", notes = "20000:成功 data{total: 总进度, current: 当前进度, result: url}；15012：添导出考生列表失败")
    @ApiOperationSort(value = 10)
    @PostMapping(value = "/downLoadStudentList")
    @Log(module = "考生管理", business = "导出考生列表")
    @ProgressAnno(total = 100, timeoutSeconds = 6000, errorCode = Constant.RESPONSE_CODE_31111001, canConcurrent = true)
    public void downLoadStudentList(@RequestBody StudentInfoParam param) {
        log.info("# 11.1.10 管理端：导出考生列表请求参数{}", FastJsonUtil.getBeanToJson(param));
        param.setOfficeId(this.getOfficeId());
        param.setDeptId(this.getDeptId());
        param.setDeptIds(iBaseLoginService.getDeptIds());
        iStudentInfoService.downLoadStudentList(param);
    }

    @ApiOperation(value = "11.1.11  管理端：获取考生审核不通过原因", notes = "20000:成功;15008 审核失败")
    @ApiOperationSort(value = 11)
    @Log(module = "考生审核原因查询", business = "查看审核考生原因")
    @ThrowsAdvice(code = 31110111, print = "查询审核考生不通过原因异常")
    @GetMapping(value = "/queryAuditStudentCauseList/{projectId}/{studentId}")
    public ApiResponse<List<StudentVerifyVo>> queryAuditStudentCauseList(@PathVariable String projectId, @PathVariable String studentId) throws Exception {
        List<StudentVerifyVo> studentVerifies = iStudentVerifyService.queryAuditStudentCauseList(projectId, studentId);
        return ApiResponse.<List<StudentVerifyVo>>builder().code(Constant.RESPONSE_CODE_SUCCESS).data(studentVerifies).build();
    }
    
    
    @ApiOperation(value = "11.2.1 管理端： 通过华为云导出未报考科目考生列表", notes = "20000:成功 data{total: 总进度, current: 当前进度, result: url}；15012：添导出考生列表失败")
    @ApiOperationSort(value = 21)
    @PostMapping(value = "/downLoadNoSubjectStudentList")
    @Log(module = "考生管理", business = "导出考生列表")
    @ProgressAnno(total = 100, timeoutSeconds = 6000, errorCode = Constant.RESPONSE_CODE_31111001, canConcurrent = true)
    public void downLoadNoSubjectStudentList(@RequestBody StudentInfoParam param) {
        log.info("# 11.1.10 管理端：导出考生列表请求参数{}", FastJsonUtil.getBeanToJson(param));
        param.setOfficeId(this.getOfficeId());
        param.setDeptId(this.getDeptId());
        param.setDeptIds(iBaseLoginService.getDeptIds());
        param.setStudentHasBmSubject(Boolean.FALSE);
        iStudentInfoService.downLoadStudentList(param);
    }
}
